package com.lyf.task.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.lyf.task.dao.UserMapper;
import com.lyf.task.domain.Product;
import com.lyf.task.result.rfidResult;
import com.lyf.task.service.ProductService;
import com.lyf.task.service.RFIDUtilService;
import com.lyf.task.util.DateFormatUtil;

@Controller
public class ProductController {

	@Autowired
	private ProductService productServiceImpl;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private RFIDUtilService rfidUtilServiceImpl;

	@RequestMapping("/product/search")
	public String searchByName(String name, Model model) {
		List<Product> productList = productServiceImpl.searchByName(name);
		model.addAttribute("plist", productList);
		return "product";
	}

	@RequestMapping(value = "/productList.html")
	public String productList(HttpServletRequest request, Model model) {
		List<Product> plist = productServiceImpl.getAllProduct();
		model.addAttribute("plist", plist);
		return "product";
	}

	@RequestMapping(value = "/admin.html")
	public String gotoAdmin(Model model) {

		return "productadd";

	}
	@RequestMapping(value = "/productAdd.html")
	public String productAdd(Model model) {

		return "productadd";

	}

	@RequestMapping(value = "/productAddOk.html")
	public String productAddOk(Model model, @RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, Product product) {
		// �ϴ�ͼƬ
		String path = request.getSession().getServletContext().getRealPath("upload/");
		String fileName = "Product" + System.currentTimeMillis() + ".png";
		File targetFile = new File(path, fileName);

		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}

		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		product.setPictureName(fileName);
		product.setPictureSrc("upload/" + fileName);

		product.setTradeTimes(0);

		product.setLastTradeTime(new Date());
		productServiceImpl.insertProduct(product);
		System.out.println(request.getServletContext().getRealPath("/"));

		// �޸�RFID��¼
		rfidResult rs = new rfidResult();
		rs.setPid(productServiceImpl.getAllProduct().get(0).getPid());
		rs.setDegree(product.getDegree());
		rs.setTradeTime(product.getTradeTimes());
		rs.setDate(DateFormatUtil.dateformat(new Date()));
		rfidUtilServiceImpl.writeNewRfid(rs);

		return "success";

	}

	@RequestMapping(value = "/productAdmin.html")
	public String productAdmin(Model model) {
		List<Product> plist = productServiceImpl.getAllProduct();

		model.addAttribute("plist", plist);
		return "productAdmin";

	}
}
